package com.googlecode.allinclusive.fw.springframework.server;

import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class TimerServer {

	private static final Log log = LogFactory.getLog(TimerServer.class);
	
	private long interval = 60000l;
	
	private long delay = 0l;
	
	private Timer timer;
	
	private Processor processor;
	
	/**
	 * Start Server.
	 */
	@PostConstruct
	public void init() {
		log.info(this.getClass().getSimpleName() + " start...");
		TimerTask t = new TimerTask() {
			public void run() {
				try {
					// process
					processor.process();
				} catch (Throwable th) {
					// ignore
					log.warn(th.getMessage(), th);
				}
			}
		};
		
		timer = new Timer();
		timer.schedule(t, delay, interval);
	}
	
	/**
	 * Stop Server.
	 */
	@PreDestroy
	public void destroy() {
		log.info(this.getClass().getSimpleName() + " stop...");
		if (timer != null) {
			timer.cancel();
		}
	}
	
	public void setInterval(long interval) {
		this.interval = interval;
	}
	
	public void setDelay(long delay) {
		this.delay = delay;
	}
	
	public void setProcessor(Processor processor) {
		this.processor = processor;
	}	
}
